package com.shu.logsearch.util;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;

/**
 * 计算工具
 *
 * @author Tree Cai
 * @date 2019/7/3
 */
public class MyMathUtil {

    /**
     * 除法
     * @param dividendNum
     *      被除数
     * @param devisorNum
     *      除数
     * @param scale
     *      保留小数点后几位
     * @return
     */
    public static Number devide(Number dividendNum, Number devisorNum, int scale) {
        BigDecimal devidend = toBigDecimal(dividendNum);
        BigDecimal devisor = toBigDecimal(devisorNum);
            return devidend.divide(devisor, scale, RoundingMode.HALF_UP);
    }

    /**
     * 将某个对象包装为BigDecimal对象
     * @param number
     * @return
     */
    private static BigDecimal toBigDecimal(Object number) {
        AssertUtil.notNull(number);
        if (number instanceof BigDecimal)
            return (BigDecimal) number;
        if (number instanceof String)
            return new BigDecimal((String) number);
        if (number instanceof BigInteger)
            return new BigDecimal((BigInteger) number);
        if (number instanceof Number)
            return new BigDecimal(((Number) number).doubleValue());
        return (BigDecimal) number;
    }

    public static void main(String[] args) {
        System.out.println(devide(2,3,4));

    }
}
